/*
 *  ircd-hybrid: an advanced Internet Relay Chat Daemon(ircd).
 *  translate.c: 
 *
 *  Copyright (C) 2002 by Elias I. Shtift. ishtift@gmail.com
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 *  USA
 *
 *  $Id: $
 */

#include "common.h"
#include "stdinc.h"
#include "fileio.h"
#include "memory.h"
#include "client.h"
#include "translate.h"
#include "s_user.h"
#include "s_log.h"
#include "s_conf.h"
#include "sprintf_irc.h"

struct Codepage *codepages = NULL;

struct Codepage *translate_codepage_add(const char *charset, const char *file)
{
  struct Codepage *cp;
  FBFILE *cp_file;
  int cnt = 0;
#ifdef _WIN32
  int len = 0;
#endif
  char cpfile[IRCD_BUFSIZE];

  if (charset == NULL)
    return NULL;

  if ((cp = translate_codepage_find_byname(charset)))
  {
    return cp;
  }

  if (codepages)
  {
    cp = codepages;
    while (cp->next)
    {
      cp = cp->next;
    }
    cp->next = (struct Codepage*) MyMalloc(sizeof(struct Codepage));
    cp->next->prev = cp;
    cp->next->next = NULL;
    cp = cp->next;
  }
  else
  {
    codepages = cp = (struct Codepage*) MyMalloc(sizeof(struct Codepage));
    cp->prev = cp->next = NULL;
  }

  strlcpy(cp->name, charset, 20);

  ircsprintf(cpfile, "%s%s", CPPATH, file);
  if ((cp_file = fbopen(file, "r")) == NULL)
  {
    if ((cp_file = fbopen(cpfile, "r")) == NULL)
    {
      if (cp->prev)
        cp->prev->next = NULL;
      if ((cp->prev == NULL) && (cp->next == NULL))
        codepages = NULL;
      MyFree(cp);
      return NULL;
    }
  }
#ifdef _WIN32
  if (!ReadFile((HANDLE)cp_file->F.fd, cp->to, 256, (LPDWORD)&len, NULL))
    cnt = -1;
  else
  {
    cnt = len;
    if (!ReadFile((HANDLE)cp_file->F.fd, cp->from, 256, (LPDWORD)&len, NULL))
    cnt+= len;
  }
#else
  cnt = read(cp_file->F.fd, cp->to, 256);
  cnt+= read(cp_file->F.fd, cp->from, 256);
#endif
  fbclose(cp_file);
  if (cnt == 512)
  {
    return cp;
  }
  else
  {
    if (cp->prev)
      cp->prev->next = NULL;
    MyFree(cp);
    return NULL;
  }
}

struct Codepage *translate_codepage_find_byname(const char *charset)
{
  struct Codepage *cp = codepages;

  while (cp)
  {
    if (!strcasecmp(cp->name, charset))
      break;

    cp = cp->next;
  }
  
  return cp;
}
